﻿using ERPWinFormWork.Material.Material.Dtos;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERPWinFormWork.Material
{
    public partial class AddContract : Form
    {
        private ApiClient _apiClient;
        private int? _selectedSupplierId;
        private string _selectedSupplierName;
        public AddContract()
        {
            InitializeComponent();
            _apiClient = new ApiClient(MaterialAppConfig.ApiBaseUrl);
            this.cbonumber.CheckedChanged += cbonumber_CheckedChanged;
          
        }
        public void SetSupplierName(string supplierName, int? supplierId = null)
        {
            _selectedSupplierName = supplierName;
            _selectedSupplierId = supplierId;
            
            if (tbxstore != null)
            {
                tbxstore.Text = supplierName ?? string.Empty;
                if (tbxstore.SkinTxt != null)
                {
                    tbxstore.SkinTxt.Text = supplierName ?? string.Empty;
                }
            }
        }
        /// <summary>
        /// 生成合同编号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbonumber_CheckedChanged(object sender, EventArgs e)
        {
            if (this.cbonumber.Checked)
            {
                string number = "CGHTBH" + DateTime.Now.ToString("yyyyMMddHHmmss");
                this.tbxhetongnumber.Text = number;
            }
            else
            {
                this.tbxhetongnumber.Text = string.Empty;
            }
        }
        /// <summary>
        /// 点击选择供应商
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnstore_Click(object sender, EventArgs e)
        {
            Supplier supplier = new Supplier(this);
            supplier.ShowDialog(this);
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        private string FIleName { get; set; }
        private void btnFile1_Click(object sender, EventArgs e)
        {
            // 创建OpenFileDialog实例
            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                // 设置对话框的标题
                openFileDialog.Title = "请选择文件";
                // 设置文件筛选器，限定可选择的文件类型
                openFileDialog.Filter =
                 "图片文件 (*.jpg;*.png;*.bmp;*.jpeg)|*.jpg;*.png;*.bmp;*.jpeg|" +
                 "文本文件 (*.txt)|*.txt|" +
                 "所有文件 (*.*)|*.*";
                // 设置默认选中的筛选器索引，这里默认选中第一个（文本文件）
                openFileDialog.FilterIndex = 1;
                // 设置是否恢复到上次打开对话框时的目录，true表示恢复
                openFileDialog.RestoreDirectory = true;
                // 设置是否检查用户输入的文件名是否存在，true表示检查
                openFileDialog.CheckFileExists = true;
                // 设置是否检查用户输入的路径是否存在，true表示检查
                openFileDialog.CheckPathExists = true;

                // 显示对话框，并判断用户是否点击了“确定”按钮
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    // 获取用户选择的文件路径
                    string selectedFilePath = openFileDialog.FileName;
                    FIleName = openFileDialog.FileName;
                    // 将文件路径显示在文本框中
                    pib1.Image = Image.FromFile(selectedFilePath);

                }
            }
        }

        /// <summary>
        /// 发送POST请求
        /// </summary>
        private async void AddPicture()
        {
            // 检查文件是否存在
            if (!File.Exists(FIleName))
            {
                // 处理文件不存在的情况，比如抛出异常或返回错误响应
                throw new FileNotFoundException("指定的文件不存在", FIleName);
            }

            // 创建 MultipartFormDataContent
            var formData = new MultipartFormDataContent();

            // 读取文件内容并添加到请求体
            using (var fileStream = new FileStream(FIleName, FileMode.Open, FileAccess.Read))
            {
                var fileContent = new StreamContent(fileStream);
                fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");

                // 添加文件内容到 formData，参数名需与 API 期望的一致（这里是 "file"）
                formData.Add(fileContent, "file", Path.GetFileName(FIleName));
            }

            // 调用文件上传方法
            var uploadResponse = await _apiClient.UploadFileAsync<ApiResponse<string>>(
                endpoint: "UpLoad/UploadFile",
                filePath: FIleName,
                formFieldName: "file" // 与接口接收参数名一致
            );



        }


        public class ApiResponse<T>
        {
            public int code { get; set; }
            public string message { get; set; }
            public string jwt { get; set; }
            public T pageData { get; set; }
            public T data { get; set; }
            public int totalCount { get; set; }
            public int totalPages { get; set; }
        }
        /// <summary>
        /// 添加按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStepwiseAdd_Click(object sender, EventArgs e)
        {
            // 检查是否选择了供应商
            if (string.IsNullOrWhiteSpace(_selectedSupplierName) || _selectedSupplierId == null)
            {
                MessageBox.Show("请选择供应商", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            
            AddMaterialTable addMaterialTable = new AddMaterialTable(_selectedSupplierId, _selectedSupplierName);
            if (addMaterialTable.ShowDialog() == DialogResult.OK)
            {
                // 将选中的物料添加到dgvproduct表格中
                AddMaterialsToGrid(addMaterialTable.SelectedMaterials);
            }
        }
        private int PageIndex { get; set; } = 1;
        private int PageSize { get; set; } = 15;
        private int TotalCount { get; set; } = 0;
        private int TotalPages { get; set; } = 0;

                /// <summary>
        /// 初始化dgvDeatils表格
        /// </summary>
        private void InitializeDgvProduct()
        {
            if (dgvDeatils.Columns.Count == 0)
            {
                // 添加物料编号列
                dgvDeatils.Columns.Add("MaterialNumber", "物料编号");
                dgvDeatils.Columns["MaterialNumber"].Width = 120;

                // 添加物料名称列
                dgvDeatils.Columns.Add("MaterialName", "物料名称");
                dgvDeatils.Columns["MaterialName"].Width = 150;

                // 添加规格型号列
                dgvDeatils.Columns.Add("Specifications", "规格型号");
                dgvDeatils.Columns["Specifications"].Width = 120;

                // 添加单位名称列
                dgvDeatils.Columns.Add("UnitName", "单位名称");
                dgvDeatils.Columns["UnitName"].Width = 100;

                // 添加类型名称列
                dgvDeatils.Columns.Add("TypeName", "类型名称");
                dgvDeatils.Columns["TypeName"].Width = 100;

                // 添加属性名称列
                dgvDeatils.Columns.Add("PropertiesName", "属性名称");
                dgvDeatils.Columns["PropertiesName"].Width = 100;

                // 添加供应商ID列
                dgvDeatils.Columns.Add("SupplierId", "供应商ID");
                dgvDeatils.Columns["SupplierId"].Width = 80;

                // 添加隐藏的物料ID列（用于提交接口）
                dgvDeatils.Columns.Add("Material_Id", "物料ID");
                dgvDeatils.Columns["Material_Id"].Visible = false;

                // 添加税率列
                dgvDeatils.Columns.Add("TaxRate", "税率");
                dgvDeatils.Columns["TaxRate"].Width = 80;

                // 添加未税价格列
                dgvDeatils.Columns.Add("PriceExclTax", "未税价格");
                dgvDeatils.Columns["PriceExclTax"].Width = 100;

                // 添加含税价格列
                dgvDeatils.Columns.Add("PriceInclTax", "含税价格");
                dgvDeatils.Columns["PriceInclTax"].Width = 100;
                
                // 添加采购数量列（可编辑的数值输入框）
                DataGridViewTextBoxColumn quantityColumn = new DataGridViewTextBoxColumn();
                quantityColumn.Name = "Quantity";
                quantityColumn.HeaderText = "采购数量";
                quantityColumn.Width = 100;
                dgvDeatils.Columns.Add(quantityColumn);

                // 添加金额小计列
                dgvDeatils.Columns.Add("Amount", "金额小计");
                dgvDeatils.Columns["Amount"].Width = 100;

                // 添加备注列（可编辑）
                DataGridViewTextBoxColumn remarkColumn = new DataGridViewTextBoxColumn();
                remarkColumn.Name = "Remark";
                remarkColumn.HeaderText = "备注";
                remarkColumn.Width = 150;
                dgvDeatils.Columns.Add(remarkColumn);

                // 设置表格属性
                dgvDeatils.AllowUserToAddRows = false;
                dgvDeatils.AllowUserToDeleteRows = true;
                dgvDeatils.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                dgvDeatils.MultiSelect = false;
                
                // 移除默认的蓝色底色选中效果
                dgvDeatils.DefaultCellStyle.SelectionBackColor = Color.White;
                dgvDeatils.DefaultCellStyle.SelectionForeColor = Color.Black;

                // 添加数量输入验证
                dgvDeatils.CellValidating += DgvProduct_CellValidating;
                
                // 添加单元格值变化事件，用于自动计算金额小计
                dgvDeatils.CellValueChanged += DgvDeatils_CellValueChanged;
                
                // 添加行删除事件，用于重新计算合同总金额
                dgvDeatils.RowsRemoved += DgvDeatils_RowsRemoved;
            }
        }

        /// <summary>
        /// 将选中的物料添加到dgvproduct表格中
        /// </summary>
        /// <param name="materials">选中的物料列表</param>
        private void AddMaterialsToGrid(List<MaterialPropertiesOutput> materials)
        {
            InitializeDgvProduct();
            
            foreach (var material in materials)
            {
                // 检查是否已存在相同的物料
                bool exists = false;
                foreach (DataGridViewRow row in dgvDeatils.Rows)
                {
                    if (row.Cells["MaterialNumber"].Value?.ToString() == material.MaterialNumber)
                    {
                        exists = true;
                        break;
                    }
                }
                
                if (!exists)
                {
                    int rowIndex = dgvDeatils.Rows.Add();
                    dgvDeatils.Rows[rowIndex].Cells["Material_Id"].Value = material.Id;
                    dgvDeatils.Rows[rowIndex].Cells["MaterialNumber"].Value = material.MaterialNumber;
                    dgvDeatils.Rows[rowIndex].Cells["MaterialName"].Value = material.MaterialName;
                    dgvDeatils.Rows[rowIndex].Cells["Specifications"].Value = material.Specifications;
                    dgvDeatils.Rows[rowIndex].Cells["UnitName"].Value = material.Unit_Name;
                    dgvDeatils.Rows[rowIndex].Cells["TypeName"].Value = material.TypeName;
                    dgvDeatils.Rows[rowIndex].Cells["PropertiesName"].Value = material.PropertiesName;
                    dgvDeatils.Rows[rowIndex].Cells["SupplierId"].Value = material.Supplier_Id;
                    dgvDeatils.Rows[rowIndex].Cells["TaxRate"].Value = "3"; // 默认税率3%
                    dgvDeatils.Rows[rowIndex].Cells["PriceExclTax"].Value = "12.00"; // 默认未税价格
                    dgvDeatils.Rows[rowIndex].Cells["PriceInclTax"].Value = "16.00"; // 默认含税价格
                    dgvDeatils.Rows[rowIndex].Cells["Quantity"].Value = ""; // 默认数量为空
                    dgvDeatils.Rows[rowIndex].Cells["Amount"].Value = ""; // 默认金额为空
                    dgvDeatils.Rows[rowIndex].Cells["Remark"].Value = ""; // 默认备注为空
                }
            }
            
            // 添加完物料后，重新计算合同总金额
            CalculateTotalContractAmount();
        }

        /// <summary>
        /// 数量输入验证
        /// </summary>
        private void DgvProduct_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (e.ColumnIndex == dgvDeatils.Columns["Quantity"].Index)
            {
                if (!string.IsNullOrEmpty(e.FormattedValue?.ToString()))
                {
                    if (!int.TryParse(e.FormattedValue.ToString(), out int quantity) || quantity <= 0)
                    {
                        e.Cancel = true;
                        MessageBox.Show("采购数量必须是大于0的整数", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
        }

        /// <summary>
        /// 单元格值变化事件，自动计算金额小计
        /// </summary>
        private void DgvDeatils_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.RowIndex < dgvDeatils.Rows.Count)
            {
                // 当采购数量或含税价格发生变化时，重新计算金额小计
                if (e.ColumnIndex == dgvDeatils.Columns["Quantity"].Index || 
                    e.ColumnIndex == dgvDeatils.Columns["PriceInclTax"].Index)
                {
                    CalculateAmount(e.RowIndex);
                }
            }
        }

        /// <summary>
        /// 计算指定行的金额小计
        /// </summary>
        /// <param name="rowIndex">行索引</param>
        private void CalculateAmount(int rowIndex)
        {
            try
            {
                var row = dgvDeatils.Rows[rowIndex];
                
                // 获取采购数量
                string quantityStr = row.Cells["Quantity"].Value?.ToString();
                if (string.IsNullOrEmpty(quantityStr) || !int.TryParse(quantityStr, out int quantity))
                {
                    row.Cells["Amount"].Value = "";
                    CalculateTotalContractAmount();
                    return;
                }
                
                // 获取含税价格
                string priceStr = row.Cells["PriceInclTax"].Value?.ToString();
                if (string.IsNullOrEmpty(priceStr) || !decimal.TryParse(priceStr, out decimal price))
                {
                    row.Cells["Amount"].Value = "";
                    CalculateTotalContractAmount();
                    return;
                }
                
                // 计算金额小计 = 采购数量 × 含税价格
                decimal amount = quantity * price;
                row.Cells["Amount"].Value = amount.ToString("F2");
                
                // 重新计算合同总金额
                CalculateTotalContractAmount();
            }
            catch (Exception ex)
            {
                // 如果计算出错，设置为空
                dgvDeatils.Rows[rowIndex].Cells["Amount"].Value = "";
                CalculateTotalContractAmount();
            }
        }

        /// <summary>
        /// 计算合同总金额（所有采购明细的金额小计之和）
        /// </summary>
        private void CalculateTotalContractAmount()
        {
            try
            {
                decimal totalAmount = 0;
                
                // 遍历所有行，计算金额小计的总和
                foreach (DataGridViewRow row in dgvDeatils.Rows)
                {
                    if (row.Cells["Amount"].Value != null && !string.IsNullOrEmpty(row.Cells["Amount"].Value.ToString()))
                    {
                        if (decimal.TryParse(row.Cells["Amount"].Value.ToString(), out decimal amount))
                        {
                            totalAmount += amount;
                        }
                    }
                }
                
                // 更新合同金额字段
                tbxprice.Text = totalAmount > 0 ? totalAmount.ToString("F2") : "";
                if (tbxprice.SkinTxt != null)
                {
                    tbxprice.SkinTxt.Text = totalAmount > 0 ? totalAmount.ToString("F2") : "";
                }
            }
            catch (Exception ex)
            {
                // 如果计算出错，清空合同金额
                tbxprice.Text = "";
                if (tbxprice.SkinTxt != null)
                {
                    tbxprice.SkinTxt.Text = "";
                }
            }
        }

        /// <summary>
        /// 行删除事件处理程序，重新计算合同总金额
        /// </summary>
        private void DgvDeatils_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            // 当删除行时，重新计算合同总金额
            CalculateTotalContractAmount();
        }
        /// <summary>
        /// 采购合同添加
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btnsuccess_Click(object sender, EventArgs e)
        {
            // 1) 表单必填校验
            if (!ValidateContractForm()) return;

            // 2) 没有明细直接返回
            if (dgvDeatils.Rows.Count == 0)
            {
                MessageBox.Show("请添加采购明细", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // 3) 公共字段
            string contractNumber = tbxhetongnumber.Text.Trim();
            string contractName = tbxnamehetong.Text.Trim();
            DateTime signDate = DateTime.Parse(dtpdatehetong.Text);
            DateTime maturityDate = DateTime.Parse(dtpdaohuo.Text);
            decimal contractAmount = decimal.TryParse(tbxprice.Text, out decimal amt) ? amt : 0m;
            string formNote = tbxnote.Text?.Trim() ?? string.Empty;
            string accessory = string.IsNullOrWhiteSpace(FIleName) ? string.Empty : Path.GetFileName(FIleName);

            this.Cursor = Cursors.WaitCursor;
            btnsuccess.Enabled = false;
            try
            {
                int success = 0;
                int total = 0;
                foreach (DataGridViewRow row in dgvDeatils.Rows)
                {
                    if (row.IsNewRow) continue;
                    total++;

                    // 确保本行金额已计算
                    CalculateAmount(row.Index);

                    var dto = BuildAddDtoFromRow(row, contractNumber, contractName, signDate, maturityDate, contractAmount, formNote, accessory);
                    if (dto == null) { continue; }

                    var resp = await _apiClient.PostAsync<AddProcurement_ContractInput, ApiResponse<string>>(
                        endpoint: "Material/AddProcurement_Contract",
                        data: dto
                    );

                    if (resp != null && resp.code == 200)
                    {
                        success++;
                    }
                    else
                    {
                        MessageBox.Show($"第{row.Index + 1}行添加失败：{resp?.message ?? "未知错误"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }

                if (success > 0)
                {
                    if (!string.IsNullOrWhiteSpace(accessory))
                    {
                        AddPicture();
                    }
                    MessageBox.Show($"添加完成：成功 {success}/{total}", "完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.Tag = "Success";
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"提交失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                this.Cursor = Cursors.Default;
                btnsuccess.Enabled = true;
            }
        }

        // 简化的表单验证（对齐后端模型必填项）
        private bool ValidateContractForm()
        {
            if (string.IsNullOrWhiteSpace(tbxhetongnumber.Text) || tbxhetongnumber.Text == "请输入")
            {
                MessageBox.Show("请输入合同编号", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            if (string.IsNullOrWhiteSpace(tbxnamehetong.Text) || tbxnamehetong.Text == "请输入")
            {
                MessageBox.Show("请输入合同名称", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            if (_selectedSupplierId == null || _selectedSupplierId <= 0)
            {
                MessageBox.Show("请选择供应商", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            if (string.IsNullOrWhiteSpace(dtpdatehetong.Text) || !DateTime.TryParse(dtpdatehetong.Text, out _))
            {
                MessageBox.Show("请选择有效的签订日期", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            if (string.IsNullOrWhiteSpace(dtpdaohuo.Text) || !DateTime.TryParse(dtpdaohuo.Text, out _))
            {
                MessageBox.Show("请选择有效的到期日期", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            if (string.IsNullOrWhiteSpace(tbxprice.Text) || !decimal.TryParse(tbxprice.Text, out decimal money) || money <= 0)
            {
                MessageBox.Show("合同金额必须大于0", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            return true;
        }

        // 将一行数据映射为后端需要的 AddProcurement_ContractInput（完全对齐后端字段）
        private AddProcurement_ContractInput BuildAddDtoFromRow(
            DataGridViewRow row,
            string contractNumber,
            string contractName,
            DateTime signDate,
            DateTime maturityDate,
            decimal contractAmount,
            string formNote,
            string accessory)
        {
            int materialId = int.TryParse(row.Cells["Material_Id"].Value?.ToString(), out int mid) ? mid : 0;
            if (materialId <= 0)
            {
                MessageBox.Show($"第{row.Index + 1}行物料ID无效，请重新选择物料。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return null;
            }

            int quantity = int.TryParse(row.Cells["Quantity"].Value?.ToString(), out int q) ? q : 0;
            if (quantity <= 0)
            {
                MessageBox.Show($"第{row.Index + 1}行数量必须大于0", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return null;
            }

            decimal subtotal = decimal.TryParse(row.Cells["Amount"].Value?.ToString(), out decimal st) ? st : 0m;
            if (subtotal <= 0)
            {
                MessageBox.Show($"第{row.Index + 1}行金额小计必须大于0", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return null;
            }

            string note = string.IsNullOrWhiteSpace(row.Cells["Remark"].Value?.ToString()) ? formNote : row.Cells["Remark"].Value.ToString();

            return new AddProcurement_ContractInput
            {
                ContractNumber = contractNumber,
                ContractName = contractName,
                SignDate = signDate,
                Supplier_Id = _selectedSupplierId,
                Contract_Amount = contractAmount,
                Maturity_Date = maturityDate,
                Audit = "未审核",
                Material_Id = materialId,
                Procurement_PricingId = 0,
                Quantity = quantity,
                Subtotal = subtotal,
                Note = note,
                Accessory = accessory
            };
        }
    }
}
